package com.cincc.cincc_pbx.ui;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.common.CallUtil;
import com.cincc.cincc_pbx.constant.CallConstant;
import com.cincc.cincc_pbx.model.EventBusModel;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "BaseActivity";
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(contentLayout());
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        // 控制默认标题显示还是隐藏
        afterViews();
        mediaPlayer = MediaPlayer.create(this, R.raw.oldphone_mono);
        mediaPlayer.setLooping(true);
        EventBus.getDefault().register(this);
    }

    /**
     * @return 布局文件
     */
    protected abstract int contentLayout();

    String incomingNumber = "";
    TextView inviteNumberTv;
    RelativeLayout layoutInviteView;
    RelativeLayout layoutRejectView;

    /**
     * @return setContentView之后调用
     */
    protected void afterViews() {
        inviteNumberTv = findViewById(R.id.invite_number_tv);
        layoutInviteView = findViewById(R.id.invite_layout);
        layoutRejectView = findViewById(R.id.reject_layout);

        ImageView rejectImg = findViewById(R.id.reject_img);
        ImageView answerImg = findViewById(R.id.answer_img);

        rejectImg.setOnClickListener(this);
        answerImg.setOnClickListener(this);
        layoutInviteView.setOnClickListener(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleCommonEvent(EventBusModel event) {
        Log.e(TAG, "handleCommonEvent: " + event.toString());
        if (event.getEventName().equals(CallConstant.INVITE_CALL)) {
            openCall(true, event.getData());
        }
        if (event.getEventName().equals(CallConstant.MAKE_CALL)) {
            openCall(false, event.getData());
        }
        if (event.getEventName().equals(CallConstant.REFRESH_RECORD_EVENT)) {
            layoutInviteView.setVisibility(View.GONE);
        }
        if (event.getEventName().equals(CallConstant.RE_REGISTER)) {
            Log.e(TAG, "handleCommonEvent: start re register");
            CallUtil.getInstance().register(this);
        }
    }

    private void openCall(boolean isInvite, String callNumber) {
        if (isInvite) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
            incomingNumber = callNumber;
            showInviteView(callNumber);
        } else {
            CallUtil.getInstance().makeCall(callNumber);
            startCall(callNumber);
        }
    }

    private void startCall(String callNumber) {
        Intent i = new Intent(this, CallActivity.class);
        i.putExtra("callNumber", callNumber);
        startActivity(i);
    }

    private void answer() {
        mediaPlayer.stop();
        layoutInviteView.setVisibility(View.GONE);
        CallUtil.getInstance().answer();
        startCall(incomingNumber);
    }

    public void reject() {
        mediaPlayer.stop();
        CallUtil.getInstance().reject();
        layoutInviteView.setVisibility(View.GONE);
        showInjectView();
        new Handler().postDelayed(() -> layoutRejectView.setVisibility(View.GONE), 2000);
    }

    private void showInviteView(String phone) {
        try {
            inviteNumberTv.setText(phone);
            layoutInviteView.setVisibility(View.VISIBLE);
            ObjectAnimator animator = ObjectAnimator.ofFloat(layoutInviteView, "translationY", 0f, 100f);
            animator.setDuration(500);
            animator.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showInjectView() {
        layoutRejectView.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(layoutRejectView, "translationY", 0f, 100f);
        animator.setDuration(500);
        animator.start();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.answer_img) {
            applyPermission();
        } else if (v.getId() == R.id.reject_img) {
            reject();
        }
    }

    private void applyPermission() {
        XXPermissions.with(this).permission(CallConstant.AUDIO_PERMISSION_LIST)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Toast.makeText(BaseActivity.this, "请授予全部权限，否则无法使用通话功能", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        answer();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Toast.makeText(BaseActivity.this, "被永久拒绝授权，请手动授予对应权限", Toast.LENGTH_SHORT).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(BaseActivity.this, permissions);
                        } else {
                            System.out.println("授予权限失败");
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
